package com.xuxueli.commontdemo.commont;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * socket服务端开启线程池
 */
@Component
@Slf4j
public class ServerSocketConfig {

    @Value("${server.port:8682}")
    private int serverPort;

    public static ServerSocket serverSocket = null;

    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    @Bean
    public void socketCreate() {
        try {
            serverSocket = new ServerSocket(serverPort);
            log.info("socket服务端开启");
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("接收到客户端socket" + socket.getRemoteSocketAddress());
                threadpool.execute(new ServerReceiveThreadTest(socket));
                //threadpool.execute(new ServerReceiveThread(socket));
            }
        } catch (IOException e) {
            log.info("socket服务启动异常");
            e.printStackTrace();
        }finally {
            threadpool.shutdown();
        }
    }
}


